package util;

import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.catalina.tribes.membership.StaticMember;
public class Util {
//	public static void send(String body, String email){
//		try {
//			Properties props = new Properties();
//			props.put("mail.smtp.host", "mail.hcmuaf.edu.vn");
//			Session session = Session.getDefaultInstance(props);
//			// tạo a message
//			Message message = new MimeMessage(session);
//				message.setSubject("demo");
//				message.setText(body);
//				// address the message
//				Address fromAddress = new InternetAddress("10130026@st.hcmuaf.edu.vn");
//				Address toAddress = new InternetAddress(email);
//				message.setFrom(fromAddress);
//				message.setRecipient(Message.RecipientType.TO, toAddress);
//				// send the message
//				Transport.send(message);
//				System.out.println("test");
//			} catch (MessagingException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//	}	
	public static void send( String smtpServer , String to, String from , String psw,
			String subject, String body) throws Exception{
		Properties props = System.getProperties();
		props.put("mail.smtp.host", smtpServer);
		props.put("mail.smtp.port", "587");
		props.put("mail.smtp.starttls.enable", "true");
		final String login = from;
		final String pwd = psw;
		Authenticator pa = null;
		if(login!= null && pwd != null){
			props.put("mail.smtp.auth", "true");
			pa = new Authenticator() {
				public PasswordAuthentication getPasswordAuthentication(){
					return new PasswordAuthentication(login, pwd);
					
				}
			};
		}// esle no authentication
		Session session = Session.getInstance(props,pa);
		Message msg = new MimeMessage(session);
		msg.setFrom(new InternetAddress(from));
		msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to,false));
		msg.setSubject(subject);
		msg.setText(body);
		msg.setHeader("X-Mailer", "LOTONtechEmail");
		msg.setSentDate(new Date());
		msg.saveChanges();
		Transport.send(msg);
		System.out.println("Message sent Ok.");
		
		
	}
	public static void sendMail(String email, String body) throws Exception{
	send("smtp.gmail.com", email, "hoangaxzn@gmail.com", "qwe123456qwe", "Trợ giúp", body);
		
		
	}
	public static void main(String[] args) {
		try {
			sendMail("hoangaxzn3@zing.vn", "dsfsdfsdfs");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}